package com.ril.financial.parsers;

import java.io.IOException;
import java.math.BigDecimal;
import java.util.Date;
import com.csvreader.CsvReader;
import com.ril.DateUtil;
import com.ril.financial.model.BankStatement;
import com.ril.financial.model.Transaction;
import com.ril.financial.model.TransactionCollection;
import org.apache.log4j.Logger;

public class CsvParser extends BaseFileParser {

    static Logger _logger = Logger.getLogger(HsbcCreditParser.class);
    private TransactionCollection<Transaction> _transactions;

    public CsvParser(String filename) {
        super(filename);
    }

    public boolean parse() {

        setAlreadyParsed(true);
        try {

            TransactionCollection<Transaction> transactions = new TransactionCollection<Transaction>();

            CsvReader csv = new CsvReader(getFilename());

            csv.readHeaders();

            while (csv.readRecord()) {
                String date = csv.get("date");
                String label = csv.get("label");
                String amount = csv.get("amount");
                transactions.add(new Transaction(DateUtil.parseIsoDate(date), label, new BigDecimal(amount)));
            }
            setStatement(new BankStatement(null, transactions, transactions.calculateTotal(), new Date(), new Date()));

            csv.close();
        } catch (IOException e) {
            _logger.error(e);
            setAlreadyParsed(false);
        }
        return alreadyParsed();
    }

    public BigDecimal parseAmount(String amount) {

        return new BigDecimal(amount);
    }

    public Date parseDate(String date) {

        return DateUtil.parseIsoDate(date);
    }
}
